<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { search as searchTree } from '@uni/api/uni/category/info'
import {
  insertTemplateComp,
  searchTemplateCompByPage,
  updateTemplateCompById,
  selectTemplateCompById
} from '@code/api/code/compont/template'
import { resetFormPlus } from '@/utils/zmids'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getModelEntityTree } from '@uni/api/uni/entity/info'
// import { AvueFormDesign } from '@code/components/anvil-code-low-design'

interface Form {
  cateId: string | undefined
  templateName: string
  templateDesc: string
  templateIcon: string
  pageModelId: Array<string>
  content: string
  reamrk: string
  templateId?: string
}

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  isDelete: 'N',
  cateId: undefined,
  templateNameLike: ''
})

const showSearch = ref<Boolean>(true)

const showDialog = ref<Boolean>(false)

const showCompSetting = ref<Boolean>(false)

const compSettingTitle = ref<string>('')

const title = ref<string>('')

const filterText = ref<string>('')

const type = ref<string>('add')

const total = ref<Number>(0)

const form = ref<Form>({
  cateId: undefined,
  templateName: '',
  templateDesc: '',
  templateIcon: '',
  content: '',
  pageModelId: [],
  reamrk: ''
})

const rules = {
  cateId: [{ required: true, message: '所属分类不能为空', trigger: 'change' }],
  templateName: [{ required: true, message: '模板名称不能为空', trigger: 'blur' }]
}

const formModelData = {
  pageName: '',
  pageCode: '',
  pageDesc: '',
  groupId: '',
  pageIcon: '',
  withMenu: 'N',
  appId: '',
  pageType: '',
  pageModelId: []
}

const formRef = ref<FormInstance>()

const formDesignRef = ref<FormInstance>()

const queryForm = ref<FormInstance>()

const CategoryTree = ref()

const groupTree = ref([])

const compList = ref([])

const entityTree = ref([])

const defaultProps = {
  label: 'cateName',
  children: 'children'
}

const formModelEntities = {
  isDeploy: 'N',
  entities: []
}

const initForm = () => {
  form.value = {
    cateId: queryParams.cateId,
    templateName: '',
    templateDesc: '',
    templateIcon: '',
    pageModelId: [],
    content: '',
    reamrk: ''
  }
  resetFormPlus(formRef.value)
}

const getGroupTree = async () => {
  return searchTree().then((res) => {
    groupTree.value = res.data
  })
}

const getTemplateComps = async () => {
  return searchTemplateCompByPage(queryParams).then((res) => {
    compList.value = res.data.list
    total.value = res.data.total
  })
}

const init = async () => {
  await getGroupTree()
  getTemplateComps()
  getEntityTreeData()
}

const handleQuery = () => {
  getTemplateComps()
}

const resetQuery = () => {
  resetFormPlus(queryForm.value)
  handleQuery()
}

const handleNodeClick = (node) => {
  queryParams.cateId = node.cateId
  getTemplateComps()
}

const handleAdd = () => {
  // if (row) {
  //   parentGroupId.value = row.groupId
  // }
  initForm()
  type.value = 'add'
  title.value = '创建模板'
  showDialog.value = true
}

const handleUpdate = (row: any) => {
  selectTemplateCompById(row.templateId).then((response) => {
    form.value = response.data
    type.value = 'update'
    title.value = '修改模板组件'
    showDialog.value = true
  })
}

const handleConfigure = (row: any) => {
  selectTemplateCompById(row.templateId).then((response) => {
    form.value = response.data
    type.value = 'update'
    compSettingTitle.value = form.value.templateName
    showCompSetting.value = true
  })
}

const handleDelete = (row: any) => {
  const params = {
    ...row,
    isDelete: 'Y'
  }
  updateTemplateCompById(params)
    .then(() => {
      ElMessage.success('删除成功')
      getTemplateComps()
    })
    .catch(function () {})
}

const submitForm = (ref: FormInstance) => {
  if (!ref) {
    return
  }
  ref.validate((valid) => {
    if (valid) {
      if (type.value == 'update') {
        updateTemplateCompById(form.value).then((response) => {
          if (response.data === 1) {
            ElMessage.success('修改成功')
            showDialog.value = false
            getTemplateComps()
          }
        })
      } else {
        // const params = {
        //   ...form.value,
        //   groupAppId: curCateId.value,
        //   groupParentId: parentGroupId.value
        // }
        insertTemplateComp(form.value).then((response) => {
          if (response.code === '200') {
            ElMessage.success('新增成功')
            showDialog.value = false
            getTemplateComps()
          }
        })
      }
    }
  })
}

const cancel = () => {
  showDialog.value = false
  initForm()
}

const compSettingCancel = () => {
  showCompSetting.value = false
  initForm()
}

const filterTreeNodes = (val, data) => {
  return data.cateName.includes(val)
}

const watchFilterText = watch(filterText, (val) => {
  CategoryTree.value.filter(val)
})

const getEntityTreeData = () => {
  const params = {
    // parentId: 0
  }
  return getModelEntityTree(params).then((res) => {
    entityTree.value = res.data
  })
}

const getChangeOptions = (options: any) => {
  form.value.content = JSON.stringify(options)
}

const compSettingSubmit = () => {
  updateTemplateCompById(form.value).then((response) => {
    if (response.data === 1) {
      ElMessage.success('模板组件配置成功')
      showCompSetting.value = false
      getTemplateComps()
    }
  })
}

init()
</script>

<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <div class="app-tree">
          <div class="tree-header">所有分类</div>
          <div class="tree-content">
            <el-input v-model="filterText" placeholder="请输入" />
            <el-tree
              :data="groupTree"
              :props="defaultProps"
              :expand-on-click-node="false"
              ref="CategoryTree"
              default-expand-all
              highlight-current
              :default-checked-keys="[0]"
              :filter-node-method="filterTreeNodes"
              @node-click="handleNodeClick"
            />
          </div>
        </div>
      </el-col>
      <el-col :span="20">
        <div class="app-form">
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="100px"
          >
            <el-form-item label="模板组件名称" prop="templateNameLike">
              <el-input
                v-model="queryParams.templateNameLike"
                placeholder="请输入组件名称"
                clearable
                size="default"
                style="width: 240px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <search-button @click="handleQuery" />
              <reset-button @click="resetQuery" />
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <add-button @click="handleAdd" text="创建模板组件" />
            <right-toolbar v-model:showSearch="showSearch" @query-table="getTemplateComps" />
          </el-row>
          <el-table :data="compList">
            <el-table-column prop="templateId" label="模板标识" align="center" />
            <el-table-column prop="templateName" label="模板名称" align="center" />
            <el-table-column prop="templateDesc" label="模板描述" align="center" />
            <el-table-column label="操作" align="center" width="300">
              <template #default="scope">
                <text-edit-button @click="handleUpdate(scope.row)" />
                <el-button
                  link
                  type="primary"
                  icon="el-icon-operation"
                  size="small"
                  @click="handleConfigure(scope.row)"
                >配置</el-button
                >
                <text-delete-button
                  @click="handleDelete(scope.row)"
                  :title="'是否确认删除' + scope.row.templateName + '?'"
                />
              </template>
            </el-table-column>
          </el-table>
        </div>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getTemplateComps"
        />
      </el-col>
    </el-row>

    <drag-dialog v-model="showDialog" :title="title">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属分类" prop="cateId">
          <el-tree-select 
            v-model="form.cateId" 
            :data="groupTree" 
            check-strictly
            :render-after-expand="false" 
            :props="{ value: 'cateId', label: 'cateName', children: 'children' }"
            placeholder="选择所属分类" 
          />
        </el-form-item>
        <el-form-item label="名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="描述" prop="templateDesc">
          <el-input v-model="form.templateDesc" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="图标选择" prop="templateIcon">
          <el-input v-model="form.templateIcon" placeholder="请选择图标" />
        </el-form-item>
        <el-form-item label="页面模型" prop="pageModelId">
          <el-select v-model="form.pageModelId" multiple filterable>
            <el-option
              v-for="(opt, idx) in entityTree"
              :key="idx"
              :label="opt.entityDesc + '(' + opt.entityName + ')'"
              :value="opt.entityId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="reamrk">
          <el-input v-model="form.reamrk" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef)">保 存</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </drag-dialog>

    <el-dialog
      v-model="showCompSetting"
      :title="compSettingTitle"
      fullscreen
      :show-close="false"
      append-to-body
    >
      <avue-form-design
        v-if="showCompSetting"
        ref="formDesignRef"
        seeData="2"
        :formJson="form.content"
        :pageVersionId="form.templateId"
        :formModelEntities="formModelEntities"
        :formModelDataFromDesign="formModelData"
        @change-options="getChangeOptions"
      />
      <template #footer>
        <dialog-footer @ok="compSettingSubmit" @cancel="compSettingCancel" okText="提交" />
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.app-tree {
  display: flex;
  flex-direction: column;
  min-height: 500px;
  border: 1px solid #ebeef5;

  .tree-header {
    height: 60px;
    line-height: 60px;
    font-size: 18px;
    background-color: rgb(235 237 240);
    padding: 0 12px;
  }

  .tree-content {
    padding: 8px 4px;
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
}

.app-form {
  padding: 12px;
}
</style>
